package com.zingrow.web.report.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.idaycrm.idaybase.utils.JsonUtils;
import com.zingrow.common.ReturnStandardDataFormat;
import com.zingrow.common.utils.EncodingUtils;
import com.zingrow.common.utils.JsonMapper;
import com.zingrow.common.utils.OptClass;
import com.zingrow.common.utils.PageView;
import com.zingrow.web.base.CodeMsg;
import com.zingrow.web.base.controller.BaseController;
import com.zingrow.web.base.enums.Menu;
import com.zingrow.web.base.enums.Operation;
import com.zingrow.web.customer.service.IGroupService;
import com.zingrow.web.report.model.RptModel;
import com.zingrow.web.report.model.RptModule;
import com.zingrow.web.report.model.RptModuleInfo;
import com.zingrow.web.report.service.IRptModelService;
import com.zingrow.web.report.service.IRptModuleService;
import com.zingrow.web.support.operate.model.OptRecord;
import com.zingrow.web.support.operate.service.IOptRecordService;
import com.zingrow.web.user.model.ActiveUser;
import com.zingrow.web.user.model.UserPermission;
import com.zingrow.web.user.service.IPermissionService;

@Controller
@RequestMapping(value = "/rpt/view/", produces = "application/json;charset=UTF-8")
public class RptModelController extends BaseController{
	
	@Autowired
	private IRptModelService rptModelService;
	@Autowired
	private IRptModuleService rptModuleService;
	@Autowired
	private IPermissionService permissionService;
	@Autowired
	private IOptRecordService ioptRecordService;
	@Autowired
	private IGroupService igroupService;
	@Autowired
	private IRptModuleService irptModuleService;

	

    @RequestMapping("selectAll")
	@ResponseBody
	public String selectAll(HttpServletRequest request,HttpServletResponse response,String name,
			String note,Integer groupId,Integer pageIndex,Integer pageSize,Integer cycleId) {
		List<RptModel> list = new ArrayList<RptModel>();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,list);
		PageView pageView = null;
		try {
			if (null==pageIndex || pageIndex <= 0) {
				pageIndex = 1;
			}
			if (null==pageSize || pageSize <= 0) {
				pageSize = 10;
			}
			pageView = new PageView(pageSize, pageIndex);
			//转码
			if (StringUtils.isNotBlank(name)) {
				name = EncodingUtils.fixUrlParamEncoding(request, name);
			}
			if (StringUtils.isNotBlank(note)) {
				note = EncodingUtils.fixUrlParamEncoding(request, note);
			}
			String groupname=null;
			if(null!=groupId&&!"".equals(groupId))
			groupname=igroupService.selectGroupNameByGroupid(groupId);
			//根据参数查询报告模板数据
			list = rptModelService.selectAll(pageView, name, note, groupId, cycleId,null);
			//新增一条操作记录
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().report_query(opuser,Menu.Reportmanagement.toString(),
					Menu.Reporttemplateconfiguration.toString(),Operation.query.toString(),name,groupname,cycleId);
			if(!s.getOptName().equals("null"))	
			ioptRecordService.insert(s);
		} catch (Exception e) {
			log.error("查询发生异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"报告管理报告模板配置查询异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(list);
		}
		standardData.setReturnData(list);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		standardData.setTotalPages(pageView.getPageCount());
        standardData.setTotalRecords(pageView.getRowCount());
		
		return JsonUtils.toString(standardData,"yyyy-MM-dd HH:mm:ss");
	}
	//查询定期报告模板
    @RequestMapping("select")
    @ResponseBody
	public String select(HttpServletRequest request,HttpServletResponse response) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);
		List<RptModel> list = new ArrayList<RptModel>();
		try {
			//查询数据库中定期报告模板数据模型数据
			list = rptModelService.select();
		} catch (Exception e) {
			log.error("查询发生异常");
			log.error(e.getMessage());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(list);
		}
		standardData.setReturnData(list);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		return JsonUtils.toString(standardData,"yyyy-MM-dd HH:mm:ss");
	}
	//新增
	@RequestMapping(value="insert",method=RequestMethod.POST)
	@ResponseBody
	public String insert(HttpServletRequest request,HttpServletResponse response,
			@RequestBody Map<String,Object> map) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);
		JsonMapper mapper = new JsonMapper(); //json工具类
		RptModel rptModel = mapper.fromJson(mapper.toJson(map.get("rptModel")), RptModel.class); //转json
		String str = map.get("list").toString(); //从map中拿集合
		JSONArray array = new JSONArray().fromObject(str);  //转json集合
		//json集合转实体集合
		List<RptModuleInfo> list =  (List<RptModuleInfo>)JSONArray.toCollection(array, RptModuleInfo.class);
		try {
			//判断参数
			if (StringUtils.isEmpty(rptModel.getName()) && null==rptModel.getGroupId()) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			//中文转码
			if (StringUtils.isNotBlank(rptModel.getName())) {
				rptModel.setName(EncodingUtils.fixUrlParamEncoding(request, rptModel.getName()));
			}
			if (StringUtils.isNotBlank(rptModel.getNote())) {
				rptModel.setNote(EncodingUtils.fixUrlParamEncoding(request, rptModel.getNote()));
			}
			String groupname="null";
			groupname=igroupService.selectGroupNameByGroupid(rptModel.getGroupId());
			//新增报告模板
			if (rptModelService.insert(rptModel, list)) {
				//操作日志
				ActiveUser opuser = getUser(request);//获取操作用户
				OptRecord s = new OptClass().report_add(opuser,Menu.Reportmanagement.toString(),
						Menu.Reporttemplateconfiguration.toString(),Operation.insert.toString(),rptModel,groupname);
				ioptRecordService.insert(s);	
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				ActiveUser opuser = getUser(request);//获取操作用户
				OptRecord s = new OptClass().recordabnormality(opuser,"报告管理报告模板配置新增失败");
				ioptRecordService.insert(s);
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
			}
		} catch (Exception e) {
			log.error("新增异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"报告管理报告模板配置新增异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
	
	@RequestMapping("selectByid")
	@ResponseBody
	public String selectByid(HttpServletRequest request,HttpServletResponse response,Integer modelId) {
		List<RptModuleInfo> list = new ArrayList<RptModuleInfo>();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);
		try {
			//判断参数
			if (null==modelId||modelId.equals("")) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			//根据报告模板ID查询相应的模块数据
			list=rptModuleService.selectBymid(modelId);
		} catch (Exception e) {
			log.error("查询发生异常");
			log.error(e.getMessage());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(list);
		}
		standardData.setReturnData(list);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	@RequestMapping(value="update",method=RequestMethod.POST)
	@ResponseBody
	public String update(HttpServletRequest request,HttpServletResponse response,
			@RequestBody Map<String,Object> map,Integer id) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);
		JsonMapper mapper = new JsonMapper();
		RptModel rptm = mapper.fromJson(mapper.toJson(map.get("rptModel")), RptModel.class);  //用工具类拿到对象
		String strlist = map.get("list").toString();
		JSONArray JsonArray = new JSONArray().fromObject(strlist);  //转json集合
		//json集合转实体集合
		List<RptModuleInfo> list = (List<RptModuleInfo>) JsonArray.toCollection(JsonArray, RptModuleInfo.class);
		try {
			//判断参数
			if (null==rptm.getId() && list.size()<=0 && null==id) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			List<RptModuleInfo> ylist=irptModuleService.querymodelId(rptm.getId());
			List<RptModule> slist=irptModuleService.query();
			RptModel suu=rptModelService.selectByPrimaryKey(rptm.getId());
			String name=suu.getName();
			String groupname=igroupService.selectGroupNameByGroupid(suu.getGroupId());
			//修改报告模板
			if (rptModelService.update(rptm, list,id)) {
				//操作日志
				ActiveUser opuser = getUser(request);//获取操作用户
				OptRecord s = new OptClass().report_updata(opuser,Menu.Reportmanagement.toString(),
						Menu.Reporttemplateconfiguration.toString(),Operation.update.toString(),ylist,list,slist,name,groupname);
				if(!s.getOptName().equals("null"))
				ioptRecordService.insert(s);
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
			}
		} catch (Exception e) {
			log.error("修改发生异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"报告管理报告模板配置修改异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
	
	@RequestMapping("isOpen")
	@ResponseBody
	public String isOpen(HttpServletRequest request,HttpServletResponse response,RptModel rptModel) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);
		try {
			//判断参数
			if (null==rptModel.getId()&&null==rptModel.getIsOpen()) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			//修改报告模板开启关闭
			if (rptModelService.isOpen(rptModel)) {
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
			}
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().report_add(opuser,Menu.Reportmanagement.toString(),
					Menu.Reporttemplateconfiguration.toString(),Operation.updatePresentation.toString(),rptModel,"null","null");
			ioptRecordService.insert(s);
		} catch (Exception e) {
			log.error("操作异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"报告管理报告模板配置修改异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
	
	@RequestMapping("delete")
	@ResponseBody
	public String delete(HttpServletRequest request,HttpServletResponse response,Integer id) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);
		try {
			//判断参数
			if (null!=id) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			//根据报告模板删除相应的数据
			if (rptModelService.del(id)) {
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
			}
		} catch (Exception e) {
			log.error("删除发生异常");
			log.error(e.getMessage());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
	//根据组织ID查询报告模板数据
	@RequestMapping("queryByGroupId")
	@ResponseBody
	public String queryByGroupId(HttpServletRequest request,HttpServletResponse response,Integer pageIndex,Integer pageSize,
			String modelName,String modelNote,Integer groupId) {
		List<RptModel> listmodel = new ArrayList<RptModel>();
		PageView pageView = null;
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,listmodel);
		try {
			if (null==pageIndex || pageIndex == 0) {
				pageIndex = 1;
			}
			if (null==pageSize || pageSize == 0) {
				pageSize = 10;
			}
			pageView = new PageView(pageSize,pageIndex);
			if (null==groupId) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			//转码
			if (StringUtils.isNotBlank(modelName)) {
				modelName = EncodingUtils.fixUrlParamEncoding(request, modelName);
			}
			if(StringUtils.isNotBlank(modelNote)){
				modelNote = EncodingUtils.fixUrlParamEncoding(request, modelNote);
			}
			listmodel = rptModelService.queryByGroupId(pageView,modelName,modelNote,groupId);
		} catch (Exception e) {
			log.error("查询异常");
			log.error(e.getMessage());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		standardData.setReturnData(listmodel);
		standardData.setTotalPages(pageView.getPageCount());
        standardData.setTotalRecords(pageView.getRowCount());
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
	@RequestMapping("queryByGidCid")
	@ResponseBody
	public String queryByGidCid(HttpServletRequest request,HttpServletResponse response,
			Integer groupId,Integer cycleId) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);
		try {
			if (null==groupId || null==cycleId) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			int count = rptModelService.queryByGidCid(groupId, cycleId);
			standardData.setReturnData(count);
			standardData.setReturnCode(CodeMsg.CODE_OK);
			standardData.setReturnMessage(CodeMsg.MSG_OK);
		} catch (Exception e) {
			log.error("查询异常");
			log.error(e.getMessage());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
}
